// 1. React核心库
import React, { useRef, useState, useEffect, useCallback } from 'react';

// 2. UI组件库 - 按字母顺序
import { Button, Card, Space, Tag, Transfer, Divider, Alert, Spin, message } from 'antd';

// 3. 图标库
import { KeyOutlined, SaveOutlined, ArrowLeftOutlined, ReloadOutlined } from '@ant-design/icons';

// 4. 专业组件库
import { PageContainer, ProTable } from '@ant-design/pro-components';
import type { ProColumns, ActionType } from '@ant-design/pro-components';

// 5. 路由和状态管理
import { useParams } from '@umijs/max';

// 7. 项目内部模块
import { apiClients } from '@/services/apiClient';
import { autoLoginInDev } from '@/utils/autoLogin';

// 8. 生成的类型定义 (必须使用，禁止手工定义)
import type { RoleExtension, PermissionExtension } from '@/services/generated';

const RolePermissions: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const actionRef = useRef<ActionType>();
  const [role, setRole] = useState<RoleExtension | null>(null);
  const [permissions, setPermissions] = useState<PermissionExtension[]>([]);
  const [rolePermissions, setRolePermissions] = useState<number[]>([]);
  const [loading, setLoading] = useState(false);
  const [saving, setSaving] = useState(false);
  const [initialLoading, setInitialLoading] = useState(true);

  // 加载角色数据
  const loadRoleData = useCallback(async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.permissions.permissionsRolesRetrieve({ id: parseInt(id!) });
      setRole(response.data as any); // 临时类型转换
    } catch (error) {
      message.error('加载角色信息失败');
    }
  }, [id]);

  // 加载所有权限
  const loadPermissions = useCallback(async () => {
    try {
      setLoading(true);
      await autoLoginInDev();
      const response = await apiClients.permissions.permissionsPermissionsList({
        pageSize: 1000,
        status: 'active',
      });
      setPermissions(response.data?.items || []);
    } catch (error) {
      message.error('加载权限列表失败');
    } finally {
      setLoading(false);
    }
  }, []);

  // 加载角色已有权限
  const loadRolePermissions = useCallback(async () => {
    try {
      await autoLoginInDev();
      const response = await apiClients.permissions.permissionsRolesPermissionsRetrieve({ id: parseInt(id!) });
      // 从权限扩展数据中提取权限ID
      const permissionIds = response.data?.map((perm: any) => perm.permission?.id).filter(Boolean) || [];
      setRolePermissions(permissionIds);
    } catch (error) {
      console.error('加载角色权限失败:', error);
      setRolePermissions([]);
    }
  }, [id]);

  // 保存权限分配
  const handleSave = useCallback(async () => {
    try {
      setSaving(true);
      await autoLoginInDev();
      await apiClients.permissions.permissionsRolesAssignPermissionsCreate({
        id: parseInt(id!),
        roleExtensionRequest: {
          permission_ids: rolePermissions,
        } as any,
      });
      message.success('权限分配成功');
      // 重新加载角色权限
      await loadRolePermissions();
    } catch (error) {
      message.error('权限分配失败');
    } finally {
      setSaving(false);
    }
  }, [id, rolePermissions, loadRolePermissions]);

  // 刷新数据
  const handleRefresh = useCallback(async () => {
    setInitialLoading(true);
    await Promise.all([
      loadRoleData(),
      loadPermissions(),
      loadRolePermissions(),
    ]);
    setInitialLoading(false);
  }, [loadRoleData, loadPermissions, loadRolePermissions]);

  useEffect(() => {
    if (id) {
      handleRefresh();
    }
  }, [id, handleRefresh]);

  // Transfer组件数据源
  const transferDataSource = permissions.map(perm => ({
    key: perm.permission?.id?.toString() || '',
    title: `${perm.permission?.name} (${perm.permission?.codename})`,
    description: perm.module || '未分类',
    disabled: perm.status !== 'active',
  }));

  // ProTable列定义
  const columns: ProColumns<PermissionExtension>[] = [
    { title: 'ID', dataIndex: ['permission', 'id'], width: 80 },
    { 
      title: '权限名称', 
      dataIndex: ['permission', 'name'], 
      render: (text, record) => (
        <Space direction="vertical" size={0}>
          <span>{text}</span>
          <Tag color="geekblue" style={{ fontSize: '12px' }}>
            {record.permission?.codename}
          </Tag>
        </Space>
      ),
    },
    { 
      title: '所属模块', 
      dataIndex: 'module', 
      width: 120, 
      render: (text) => <Tag color="green">{text || '未分类'}</Tag>,
    },
    { 
      title: '权限分类', 
      dataIndex: 'category_name', 
      width: 120, 
      render: (text) => text ? <Tag color="blue">{text}</Tag> : '-',
    },
    { 
      title: '状态', 
      dataIndex: 'status', 
      width: 100,
      render: (text) => (
        <Tag color={text === 'active' ? 'green' : 'red'}>
          {text === 'active' ? '激活' : '禁用'}
        </Tag>
      ),
    },
  ];

  // 获取已分配的权限列表
  const assignedPermissions = permissions.filter(p => 
    rolePermissions.includes(p.permission?.id || 0)
  );

  if (initialLoading) {
    return (
      <PageContainer title="角色权限管理">
        <Card>
          <div style={{ textAlign: 'center', padding: '50px 0' }}>
            <Spin size="large" />
            <div style={{ marginTop: 16 }}>加载中...</div>
          </div>
        </Card>
      </PageContainer>
    );
  }

  return (
    <PageContainer 
      title={`角色权限管理 - ${role?.group?.name || ''}`}
      extra={[
        <Button key="refresh" icon={<ReloadOutlined />} onClick={handleRefresh}>
          刷新
        </Button>,
        <Button key="back" icon={<ArrowLeftOutlined />} href="/permissions/roles">
          返回角色列表
        </Button>,
      ]}
    >
      <Card>
        {/* 操作区域 */}
        <div style={{ marginBottom: 16 }}>
          <Space>
            <Button 
              type="primary" 
              icon={<SaveOutlined />} 
              loading={saving}
              onClick={handleSave}
            >
              保存权限分配
            </Button>
            <span>为角色 <Tag color="blue">{role?.group?.name}</Tag> 分配权限</span>
          </Space>
        </div>

        {/* 权限分配区域 */}
        <Alert
          message="权限分配说明"
          description="左侧为所有可用权限，右侧为已分配给该角色的权限。您可以通过拖拽或点击来调整权限分配。"
          type="info"
          showIcon
          style={{ marginBottom: 16 }}
        />

        <Spin spinning={loading}>
          <Transfer
            dataSource={transferDataSource}
            titles={['可用权限', '已分配权限']}
            targetKeys={rolePermissions.map(id => id.toString())}
            onChange={(targetKeys) => {
              setRolePermissions(targetKeys.map(key => parseInt(key.toString())));
            }}
            render={item => (
              <div>
                <div>{item.title}</div>
                <div style={{ fontSize: '12px', color: '#666' }}>模块: {item.description}</div>
              </div>
            )}
            showSearch
            filterOption={(inputValue, option) => {
              const titleMatch = option.title.toLowerCase().includes(inputValue.toLowerCase());
              const descMatch = option.description && option.description.toLowerCase().includes(inputValue.toLowerCase());
              return titleMatch || !!descMatch;
            }}
            style={{ width: '100%' }}
            listStyle={{
              width: '45%',
              height: 400,
            }}
          />
        </Spin>

        <Divider />

        {/* 已分配权限详情 */}
        <ProTable<PermissionExtension>
             scroll={{x: 'max-content'}}
          headerTitle={`已分配权限详情 (${assignedPermissions.length}个)`}
          actionRef={actionRef}
          rowKey={(record) => record.permission?.id || 0}
          search={false}
          pagination={{ pageSize: 10, showSizeChanger: true }}
          dataSource={assignedPermissions}
          columns={columns}
          toolBarRender={false}
          size="small"
        />
      </Card>
    </PageContainer>
  );
};

export default RolePermissions;
